<template>
  <div class="base-table">
    <el-table
      ref="table"
      :data="table.data"
      border
      stripe
      highlight-current-row
      :height="tableHeight"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="45"
        align="center"
        v-if="isSelection"
      ></el-table-column>
      <el-table-column
        fixed
        label="序号"
        type="index"
        align="center"
      ></el-table-column>
      <el-table-column
        v-for="item in table.column"
        :key="item"
        :label="item"
        :prop="item"
        :fixed="fixedCol.indexOf(item) >= 0"
        :sortable="fixedCol.indexOf(item) == -1"
        align="center"
        #default="{ row }"
      >
        <span :style="scoreStyle(row, item)">
          {{ numHandle(row[item]) }}
        </span>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import NP from 'number-precision'
export default {
  name: 'BaseTable',
  props: {
    tableHeight: {
      type: Number,
      default: 500
    },
    isSelection: {
      type: Boolean,
      default: false
    },
    table: {
      type: Object,
      default() {
        return {}
      }
    },
    fixedCol: {
      type: Array,
      default() {
        return ['班级', '姓名']
      }
    }
  },
  watch: {
    table() {
      this.$nextTick(() => {
        this.doLayout()
      })
    }
  },
  computed: {
    subjectObj() {
      return this.$store.getters.subjectObj
    },
    subjectRankList() {
      return this.table.column.filter(item => /进退|差/.test(item))
    }
  },
  data() {
    return {
      multipleSelection: []
    }
  },
  methods: {
    doLayout() {
      this.$refs.table && this.$refs.table.doLayout()
    },
    numHandle(val) {
      if (val && !isNaN(val)) {
        return NP.strip(val)
      }
      return val
    },
    scoreStyle(row, key) {
      let { subjectObj, subjectRankList } = this
      if (this.table.isCompare) {
        if (subjectRankList.includes(key) && row[key] < 0) {
          return { color: 'red' }
        }
      } else {
        if (subjectObj[key] && row[key] < subjectObj[key].passScore) {
          return { color: 'red' }
        }
      }
      return {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style lang="scss" scoped>
.base-table {
  width: 100%;
}
</style>
